//
//  SN_VIPCenterViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/7/3.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_VIPCenterViewController.h"
#import "SN_RegisterVIPViewController.h"

#import "SN_VIPConfigCell.h"
#import "SN_OrderListCell.h"

@interface SN_VIPCenterViewController ()<UITableViewDelegate,UITableViewDataSource,IAPToolDelegate,reloadDataDelegate>
{
    NSInteger isVIP;
    NSString *endtimeStr;
    
    EmptyStateView *noWifiView;//无网络状态
    
}

@property (nonatomic, strong) UITableView *myTable;
@property (nonatomic, strong) UILabel *emptyLabel;

@property (nonatomic, strong) NSMutableArray *vipconfigArr;
@property (nonatomic, strong) NSMutableArray *orderArr;


@end

@implementation SN_VIPCenterViewController

- (void)loadView {
    
    [super loadView];
    
    self.navBar.navigationItem.title = @"会员中心";
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    noWifiView = [[EmptyStateView alloc] initNoWifiWithFrame:CGRectMake(0, (SCREENHEIGH-SafeAreaTopHeight-175)/2+SafeAreaTopHeight, SCREENWIDTH, 175) andBackImage:@"noWifi" andBottomStr:@"网络出错啦,点击重新加载"];
    noWifiView.userInteractionEnabled= YES;
    noWifiView.delegate = self;
    [self.view addSubview:noWifiView];
    
    [self.view addSubview:self.myTable];
    
    [self getVipData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - ReloadDataDelegate

- (void)reloadCurrentData {
    
    [noWifiView hideEmptyImage];
    [self getVipData];
    
}

#pragma mark - Request

- (void)getVipData {
 
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_vipcenter" forKey:@"Method"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
       
        NSDictionary *dic = (NSDictionary *)jsonObject;
        
        NSDictionary *redata = [dic objectForKey:@"re_data"];
        
        self->isVIP = [[redata objectForKey:@"isvip"] integerValue];
        
        NSDictionary *imformation = [SyUserInfomation acquirePersonalImformationFromMemoryWithPersonID:USERID];
        NSMutableDictionary *informationM = [NSMutableDictionary dictionaryWithDictionary:imformation];
        
        [informationM setObject:[NSString stringWithFormat:@"%ld",(long)isVIP] forKey:@"isvip"];
        
        [SyUserInfomation personalImformationSaveWtih:informationM];
        
        self->endtimeStr = [redata objectForKey:@"endtime"];
        
        self.vipconfigArr = [[NSMutableArray alloc]initWithArray:[redata objectForKey:@"vipconfiglist"]];
        self.orderArr = [[NSMutableArray alloc]initWithArray:[redata objectForKey:@"viporderlist"]];
        
        self.emptyLabel.hidden = self.orderArr.count == 0?NO:YES;
        
        self.myTable.hidden = NO;
        [self.myTable reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [noWifiView showEmptyImage];
        
    }];
    
}

- (void)getOrderInfo:(NSString *)productId {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_iosviporder" forKey:@"Method"];
    [param setObject:productId forKey:@"product_id"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = (NSDictionary *)jsonObject;
        
        NSDictionary *re_data = [dict objectForKey:@"re_data"];
        
        NSString *orderCode = [re_data objectForKey:@"ordercode"];
        if (orderCode) {
            [[SN_IAPTool ShareTool] getProduct:productId order:orderCode delegate:self];
            //[SN_IAPTool ShareTool].delegate = self;
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        [Utils alertViewWithMessage:[error localizedDescription]];
    }];
}

- (void)getFreeVip:(NSString *)productId {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_givevip" forKey:@"Method"];
    [param setObject:productId forKey:@"productid"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = (NSDictionary *)jsonObject;
        
        if (recode == 0) {
            [self getVipData];
        }
        
        [Utils alertViewWithMessage:[dict objectForKey:@"re_info"]];
        
        
        
    } failure:^(NSInteger recode, NSError *error) {
        [Utils alertViewWithMessage:[error localizedDescription]];
    }];
}


#pragma mark - IAPDelegate

- (void)orderResult:(NSInteger)recode {
    
    if (recode == 0) {
        [self getVipData];
    }
}

#pragma mark - UITableViewDataSource && UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return self.vipconfigArr.count;
    }else if (section == 2) {
        return self.orderArr.count;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 116;
    }else {
        return 46;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section != 0) {
        return 42;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section != 0) {
        UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 42)];
        [header setBackgroundColor:[UIColor whiteColor]];
        
        UIView *topLine = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 10)];
        [topLine setBackgroundColor:colorFromHex(@"f4f5f7")];
        [header addSubview:topLine];
        
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(15, 26, SCREENWIDTH, 16)];
        [title setFont:[UIFont systemFontOfSize:16]];
        [title setTextColor:colorFromHex(@"fb524a")];
        title.text = section == 1?@"VIP套餐":@"开通记录";
        
        [header addSubview:title];
        
        return header;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    
    if (section == 0) {
        
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"headCellIdentifier"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImageView *headImg = [[UIImageView alloc]initWithFrame:CGRectMake(15, 24, 68, 68)];
        headImg.layer.cornerRadius = 34;
        headImg.clipsToBounds = YES;
        NSString *logo = [SYAccountTool ShareAccount].account.logo;
        if (logo && ![logo hasPrefix:@"http"]) {
            logo = [REQUESTIMAGEURL stringByAppendingString:logo];
        }
        [headImg sd_setImageWithURL:[NSURL URLWithString:logo] placeholderImage:[UIImage imageNamed:@"personalsettings_switchloading_pic_"]];
        [cell.contentView addSubview:headImg];
        
        UIImageView *headBg = [[UIImageView alloc]initWithFrame:CGRectMake(15, 24, 76, 68)];
        NSInteger isVip = [[SYAccountTool ShareAccount].account.isvip integerValue];
        [headBg setImage:[UIImage imageNamed:isVip == 1?@"VIP_effective":@"VIP_expired"]];
        [cell.contentView addSubview:headBg];
        
        UILabel *nameLab = [[UILabel alloc]initWithFrame:CGRectMake(headImg.right+20, 30, 200, 18)];
        [nameLab setFont:[UIFont systemFontOfSize:17]];
        [nameLab setTextColor:colorFromHex(@"3b3b3b")];
        nameLab.text = [SYAccountTool ShareAccount].account.username;
        
        [cell.contentView addSubview:nameLab];
        
        if (isVIP == 1) {
            
            UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(nameLab.left, nameLab.bottom+7, 100, 14)];
            [title setText:@"VIP用户"];
            [title setFont:[UIFont systemFontOfSize:14]];
            [title setTextColor:colorFromHex(@"979797")];
            [cell.contentView addSubview:title];
            
            UILabel *endtime = [[UILabel alloc]initWithFrame:CGRectMake(nameLab.left, title.bottom+4, 150, 14)];
            [endtime setText:[NSString stringWithFormat:@"有效期：%@",endtimeStr]];
            [endtime setTextColor:colorFromHex(@"979797")];
            [endtime setFont:[UIFont systemFontOfSize:14]];
            [cell.contentView addSubview:endtime];
            
        }else {
            
            UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(nameLab.left, nameLab.bottom+7, SCREENWIDTH - nameLab.left - 15, 50)];
            [title setText:isVIP == 0?@"您的VIP会员已过期，续费后可继续享受查看解题过程功能等特权":@"您还不是VIP会员，开通后可享受查看解题过程功能等特权"];
            [title setTextColor:colorFromHex(@"979797")];
            title.numberOfLines = 0;
            [title setFont:[UIFont systemFontOfSize:14]];
            [title sizeToFit];
            
            [cell.contentView addSubview:title];
        }
        
        return cell;
    }else if (section == 1) {
        
        SN_VIPConfigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"configIdentifier"];
        
        if (cell == nil) {
            cell = [[SN_VIPConfigCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"configIdentifier"];
            
        }
        
        [cell creatCell:[self.vipconfigArr objectAtIndex:indexPath.row]isVip:isVIP];
        if (indexPath.row == self.vipconfigArr.count-1) {
            for (UIView *line in cell.contentView.subviews) {
                if (line.tag == 100) {
                    [line removeFromSuperview];
                }
            }
        }
        
        return cell;
        
    }else if (section == 2) {
        
        SN_OrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderIdentifier"];
        
        if (cell == nil) {
            cell = [[SN_OrderListCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"orderIdentifier"];
        }
        
        [cell creatCell:[self.orderArr objectAtIndex:indexPath.row]];
        
        return cell;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        
        NSDictionary *dic = [self.vipconfigArr objectAtIndex:indexPath.row];
        
        if ([[dic objectForKey:@"price"] integerValue] == 0) {
            [self getFreeVip:[dic objectForKey:@"product_id"]];
        }else {
            [self getOrderInfo:[dic objectForKey:@"product_id"]];
        }
        
    }
}



#pragma mark - Get

- (UITableView *)myTable {
    
    if (_myTable == nil) {
        _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight - SafeAreaBottomHeight) style:(UITableViewStylePlain)];
        _myTable.delegate = self;
        _myTable.dataSource = self;
        _myTable.hidden = YES;
        _myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _myTable;
}

- (UILabel *)emptyLabel {
    
    if (_emptyLabel == nil) {
        _emptyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 400, SCREENWIDTH, 15)];
        [_emptyLabel setFont:[UIFont systemFontOfSize:15]];
        [_emptyLabel setText:@"暂无开通记录"];
        [_emptyLabel setTextColor:colorFromHex(@"979797")];
        [_emptyLabel setTextAlignment:NSTextAlignmentCenter];
        
        [self.myTable addSubview:_emptyLabel];
    }
    
    return _emptyLabel;
}

@end
